package com.zerui.manager.common.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ClassUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * UploadUtil类
 *
 * @author xiaozhiyun
 * @version 1.1.0
 * @since 2021-09-18
 */
@Slf4j
public class UploadUtil {

    public static final String UPLOAD_PATH = "/upload";
    public static final String DATA_PATH = "/data";
    public static final String TEMP_PATH = "/temp";
    public static final String PUBLIC_PATH = "/public";

    public static String getSuffixName(String fileName) {
        return fileName.substring(fileName.lastIndexOf("."));
    }

    public static boolean mkdirs(String path) {
        File file = new File(path);
        if (!file.exists()) {
            return file.mkdirs();
        }
        return true;
    }

    public static String makeFileDir(Date now) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("/yyyy/MM/dd");
        return dateFormat.format(now);
    }

    public static String makeRandomFileName(Date now, String suffixName) {
        SimpleDateFormat simpleDateFormat;
        simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String nowStr = simpleDateFormat.format(now);
        Random random = new Random();
        int rannum = (int) (random.nextDouble() * (99999 - 10000 + 1)) + 10000;
        return nowStr + rannum + suffixName;
    }

    public static String getBaseDir() {
        String path = ClassUtils.getDefaultClassLoader().getResource("").getPath();
        if (path.endsWith("/")) {
            path = path.substring(0, path.length() - 1);
        }
        path = path + "/../../..";
        return path + DATA_PATH;
    }

    public static void main(String[] args) {
        System.out.println(UploadUtil.getBaseDir());
    }

    public static void setFileDownloadHeader(HttpServletResponse response, String filename) {
        String headerValue = "attachment;";
        headerValue += " filename=\"" + encodeURIComponent(filename) + "\";";
        headerValue += " filename*=utf-8''" + encodeURIComponent(filename);
        response.setHeader("Content-Disposition", headerValue);
        response.setContentType("application/force-download");// 设置强制下载不打开
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
    }

    public static String encodeURIComponent(String value) {
        try {
            return URLEncoder.encode(value, "UTF-8").replaceAll("\\+", "%20");
        } catch (UnsupportedEncodingException e) {
            log.error("", e);
            return null;
        }
    }

}
